package com.hulu73.struts1.newCore;

import java.io.IOException;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 控制器，负责截取URL或分发
 * @author lzg
 *
 * 2017年9月11日
 */
public class ActionServlet extends HttpServlet{
	
	 public static final String MODULE_KEY = "org.apache.struts.action.MODULE";

	//初始化配置文件
	@Override
	public void init() throws ServletException {
		ActionMapping actionMapping = new ActionMapping("welcome", "com.hulu73.struts1.action.WelcomeAction");
		
		
		
		Properties propertiesForward = new Properties();
		propertiesForward.put("success","/success.jsp");
		propertiesForward.put("error","/error.jsp");
		ActionForward actionForward = new ActionForward(propertiesForward);
		actionMapping.setActionForward(actionForward);
		
		
		//封装的参数
		Properties properties = new Properties();
		properties.put("name", "Tom");
		ActionForm actionForm = new ActionForm(properties);
		
		actionMapping.setActionForm(actionForm);
		// 4. 保存解析结果，将结果存入ServletContext中  
		 getServletContext().setAttribute(MODULE_KEY
		            + actionMapping.getPath(), actionMapping);
		
	}
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			process(request, response);
		} catch (ClassNotFoundException | IllegalAccessException
				| InstantiationException e) {
			e.printStackTrace();
		}
	}
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			process(request, response);
		} catch (ClassNotFoundException | IllegalAccessException
				| InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 处理所有的请求
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws InstantiationException 
	 * @throws IllegalAccessException 
	 * @throws ClassNotFoundException 
	 * @throws IOException 
	 */
	 protected void process(HttpServletRequest request,
		        HttpServletResponse response) throws ServletException, ClassNotFoundException, IllegalAccessException, InstantiationException, IOException{
		 ActionMapping actionMapping = (ActionMapping) getServletContext().getAttribute(MODULE_KEY + "welcome");
		 RequestProcessor processor = new RequestProcessor();
		 processor.init(this,actionMapping);
		 processor.process(request, response);
	 }
	 
}
